#include"comm.hpp"
#include"log.hpp"
#include<iostream>
using namespace std;

//管理管道文件 : 创建，并当结束可自动删除
int main()
{
    //1.创建管道 - 构造
    // int n = mkfifo(FIFO_FILE,MODE);
    // if(n==-1)
    // {
    //     perror("mkfifo");
    //     exit(FIFO_CREAT_ERR);
    // }
    // sleep(5);
    Init init;
    Log log;
    //2.打开管道
    int fd = open(FIFO_FILE,O_RDONLY);//再写端已经打开后才能open，否则处于堵塞状态
    if(fd < 0)
    {
        // perror("open");
        //日志
        log.printmethod(Classfile);
        log.logmessage(Fatal,"error string:%s,error code:%d",strerror(errno),errno);
        exit(FIFO_OPEN_ERR);
    }

    // cout<<"server open:"<<endl;
    log.printmethod(Screen);
    log.logmessage(Info,"server open:%s,error code:%d",strerror(errno),errno);
    //3.开始通信
    while(true)
    {
        char buffer[1024] = {0};
        int x = read(fd,buffer,sizeof(buffer));
        if(x > 0)
        {
            buffer[x] = '\0';
            cout<<"client# " << buffer << endl;
        }
        else if(x == 0)
        {
            // cout<<"server closes"<<endl;
             log.printmethod(Classfile);
             log.logmessage(Debug,"server closes:%s,error code:%d",strerror(errno),errno);
            break;
        }
        else
        {
            break;
        }
    }

    //4.关闭删除管道 - 析构
     close(fd);
    
    return 0;
}
